package com.example.test;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
    private static final String TAG="PrintOut";

    private String host = "tcp://iot.ranye-iot.net:1883";
    private String userName = "Bubo_3";
    private String passWord = "root";
    private String mqtt_id = "Bubo_3_id"; //定义成自己的QQ号  切记！不然会掉线！！！
    private String mqtt_sub_topic = "Bubo/myTopic_sub"; //为了保证你不受到别人的消息  哈哈
    private String mqtt_pub_topic = "Bubo/myTopic_pub"; //为了保证你不受到别人的消息  哈哈  自己QQ好后面加 _PC

    private int led_flag =1;
    private ScheduledExecutorService scheduler;

    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;

    private Button btn_print;
    private Switch mswitch;

    private int flag_test;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button_print();
        Switch_Send();

        //**********************************************************//
        Mqtt_init();
        startReconnect();
        this.handler = new Handler() {
            /* class com.example.smarthomeandroid.MainActivity.AnonymousClass1 */

            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int i = msg.what;
                char c = 3;
                char c2 = 1;
                char c3 = 0;
                if (i == 3) {
                    String s = msg.obj.toString();
                    String[] a = s.split(",");  //以,分割，输出数组
                    System.out.println("msg"+a);
                    int i2 = 0;
                    while (i2 < a.length) {
                        Log.i(MainActivity.TAG, "a[" + i2 + "]==" + a[i2]);

                        /*状态位*/
                        i2++;
                        s = s;
                        c = 3;
                        c2 = 1;
                        c3 = 0;
                    }
                } else if (i == 30) {
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_LONG).show();
                } else if (i == 31) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();
                    try {
                        MainActivity.this.client.subscribe(MainActivity.this.mqtt_sub_topic, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

    }

    private void Switch_Send() {
        this.mswitch = findViewById(R.id.mswitch);
        this.mswitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MainActivity.this.flag_test == 0) {
                    MainActivity mainActivity = MainActivity.this;
                    mainActivity.publishmessageplus(mainActivity.mqtt_pub_topic, "{\"target\":\"TEST\",\"value\":1}");
//                  // 发送 {"target":"TEST","value":1}
                    MainActivity.this.flag_test = 1;
                    return;
                }
                MainActivity mainActivity2 = MainActivity.this;
                mainActivity2.publishmessageplus(mainActivity2.mqtt_pub_topic, "{\"target\":\"TEST\",\"value\":0}");
                //发送 {"target":"TEST","value":0}
                MainActivity.this.flag_test = 0;
            }
        });
    }


    private void Button_print(){
        this.btn_print = (Button) findViewById(R.id.btn_print);
        this.btn_print.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(MainActivity.TAG,"hello");
                System.out.println("hello");
                Toast.makeText(MainActivity.this, "hello", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void Mqtt_init()
    {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
//                    msg.obj = topicName + "---" + message.toString();
                    msg.obj =message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        // 没有用到obj字段
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    // 没有用到obj字段
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }

}